<?php

namespace app\api\controller;

use think\facade\Db;
use think\facade\Log;

class Notify
{
    public function __construct()
    {
        $this->appid = config('config.wechat.appid');
        $this->appSecret = config('config.wechat.app_secret');
        $this->mch_id = config('config.wechat.mch_id'); //商户ID
        $this->mch_key =config('config.wechat.mch_key'); //商户支付key
    }

    /**
     * 开通会员支付回调
     * @return string
     */
    public function memberPayResult(){
        $xml = file_get_contents("php://input");
        // 禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA)),true);
        //日志写入
        Log::write('PayResult: ' . json_encode($data),date('Y-m-d H:i:s'));
        //保存微信服务器返回的签名sign
        $data_sign = $data['sign'];
        //sign不参与签名算法
        unset($data['sign']);
        $sign = $this->sign($data);
        //判断签名是否正确,判断支付状态
        if (($sign===$data_sign) && ($data['return_code'] == 'SUCCESS') && ($data['result_code'] == 'SUCCESS')) {
            $results = $data;
            //更新支付状态
            $order = Db::name('user_level_log')->where('order_no',$data['out_trade_no'])->find();
            if (!empty($order['status'])) {
                //返回状态给微信服务器
                return sprintf("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
            }
            $level = Db::name('user_level')->where('id',$order['level'])->find();
            $user = Db::name('user')->where('id',$order['uid'])->find();
            //会员类型
            if ($level['id'] == 1) {
                if (!empty($user['is_vip_one'])) {
                    //续费
                    $save['vip_end_time_one'] = 31536000+$user['vip_end_time_one'];
                } else {
                    //新开
                    $save['vip_end_time_one'] = 31536000+time();
                    $save['is_vip_one'] = 1;
                }
            } elseif ($level['id'] == 2) {
                if (!empty($user['is_svip_one'])) {
                    //续费
                    $save['svip_end_time_one'] = 31536000+$user['svip_end_time_one'];
                } else {
                    //新开
                    $save['svip_end_time_one'] = 31536000+time();
                    $save['is_svip_one'] = 1;
                }
            } elseif ($level['id'] == 3) {
                if (!empty($user['is_vip_two'])) {
                    //续费
                    $save['vip_end_time_two'] = 31536000+$user['vip_end_time_two'];
                } else {
                    //新开
                    $save['vip_end_time_two'] = 31536000+time();
                    $save['is_vip_two'] = 1;
                }
            } else {
                if (!empty($user['is_svip_two'])) {
                    //续费
                    $save['svip_end_time_two'] = 31536000+$user['svip_end_time_two'];
                } else {
                    //新开
                    $save['svip_end_time_two'] = 31536000+time();
                    $save['is_svip_two'] = 1;
                }
            }

            Db::name('user')->where('id',$order['uid'])->update($save);
            Db::name('user_level_log')->where('id',$order['id'])->update([
                'status' => 1,
                'pay_time' => time(),
            ]);
            $mobile = substr_replace($user['mobile'], '****', 3, 4);
            Db::name('notice')->insert([
                'uid' => $order['uid'],
                'type' => 1,
                'content' => $mobile.'升级了'.$level['title'],
                'create_time' => time()
            ]);
        } else {
            $results = false;
        }

        //返回状态给微信服务器
        return sprintf("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
    }

    /**
     * 开通会员支付回调
     */
    public function aliNotify()
    {
        $request = request()->param();
        //支付成功:TRADE_SUCCESS   交易完成：TRADE_FINISHED
        if ($request['trade_status'] == 'TRADE_SUCCESS' || $request['trade_status'] == 'TRADE_FINISHED') {
            //这里根据项目需求来写你的操作 如更新订单状态等信息 更新成功返回'success'即可
            $object = json_decode(($request['fund_bill_list']), true);
            $trade_type = $object[0]['fundChannel'];
            $data1['batch'] = $request['trade_no']; //交易流水号
            $buyer_pay_amount = $request['buyer_pay_amount'];
            $out_trade_no = $request['out_trade_no']; //获取订单号

            //更新订单
            $order = Db::name('user_level_log')->where('order_no',$out_trade_no)->find();
            if (!empty($order['status'])) {
                exit('success');
            }
            $level = Db::name('user_level')->where('id',$order['level'])->find();
            $user = Db::name('user')->where('id',$order['uid'])->find();
            //会员类型
            if ($level['id'] == 1) {
                if (!empty($user['is_vip_one'])) {
                    //续费
                    $save['vip_end_time_one'] = 31536000+$user['vip_end_time_one'];
                } else {
                    //新开
                    $save['vip_end_time_one'] = 31536000+time();
                    $save['is_vip_one'] = 1;
                }
            } elseif ($level['id'] == 2) {
                if (!empty($user['is_svip_one'])) {
                    //续费
                    $save['svip_end_time_one'] = 31536000+$user['svip_end_time_one'];
                } else {
                    //新开
                    $save['svip_end_time_one'] = 31536000+time();
                    $save['is_svip_one'] = 1;
                }
            } elseif ($level['id'] == 3) {
                if (!empty($user['is_vip_two'])) {
                    //续费
                    $save['vip_end_time_two'] = 31536000+$user['vip_end_time_two'];
                } else {
                    //新开
                    $save['vip_end_time_two'] = 31536000+time();
                    $save['is_vip_two'] = 1;
                }
            } else {
                if (!empty($user['is_svip_two'])) {
                    //续费
                    $save['svip_end_time_two'] = 31536000+$user['svip_end_time_two'];
                } else {
                    //新开
                    $save['svip_end_time_two'] = 31536000+time();
                    $save['is_svip_two'] = 1;
                }
            }
            Db::name('user')->where('id',$order['uid'])->update($save);
            Db::name('user_level_log')->where('id',$order['id'])->update([
                'status' => 1,
                'pay_time' => time(),
            ]);
            $mobile = substr_replace($user['mobile'], '****', 3, 4);
            Db::name('notice')->insert([
                'uid' => $order['uid'],
                'type' => 1,
                'content' => $mobile.'升级了'.$level['title'],
                'create_time' => time()
            ]);
            //需求处理完成之后必须返回success
            exit('success'); //成功处理后必须输出这个字符串给支付宝
        }
    }
    protected function sign($data)
    {
        //获取微信支付秘钥
        $key = '23c37fe26978c393e2a4f0e329452cf6';
        // 去空
        $data = array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a = http_build_query($data);
        $string_a = urldecode($string_a);
        //签名步骤二：在string后加入KEY
        //$config=$this->config;
        $string_sign_temp = $string_a . "&key=" . $key;
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $result = strtoupper($sign);
        return $result;
    }

}